package com.captjack.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * @author admin
 */
public class NettyClient {

    /**
     * bootstrap
     */
    private Bootstrap bootstrap;

    public static void main(String[] args) {
        new NettyClient().startConnect();
    }

    /**
     * 启动连接、开始处理
     */
    private void startConnect() {
        try {
            // 初始化
            initBootstrap();
            // channel
            Channel channel = bootstrap.connect("192.168.104.55", 7005).sync().channel();
            String loginInfo = "LOGI " + "SAVE:56" + " " + "save2" + " " + "save2" + "\r\n";
            //
            channel.writeAndFlush(loginInfo).sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * init bootstrap
     */
    private void initBootstrap() {
        // bootstrap
        this.bootstrap = new Bootstrap();
        // 事件驱动组
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        // group
        this.bootstrap.group(nioEventLoopGroup);
        // channel
        this.bootstrap.channel(NioSocketChannel.class);
        // handler
        this.bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) {
                channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
                // 进行字符串的编解码设置
                channel.pipeline().addLast(new NettyPrintChannelHandler());
            }
        });
    }

}
